package com.cl.web.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

@Controller
@Scope("prototype")
public class UploadAction  {
	
	private File file;
	private String fileFileName;
	
	public void setFile(File file) {
		this.file = file;
	}

	public void setFileFileName(String fileFileName) {
		this.fileFileName = fileFileName;
	}

	public String imgUpload() throws Exception{
		String root = ServletActionContext.getServletContext().getRealPath("/uploadImg");
		if(file != null){
			InputStream is = new FileInputStream(file);
			FileOutputStream fos = new FileOutputStream(new File(root,fileFileName));
			byte[] b = new byte[1024];
			int len = 0;
			while((len=is.read(b))!=-1){
				fos.write(b, 0, len);
			}
			HttpServletResponse response = ServletActionContext.getResponse();
			response.setContentType("application/json;charset=utf-8");
			PrintWriter pw = response.getWriter();
			String path="uploadImg/"+fileFileName;
			String json="{\"code\":\"0\",\"msg\":\"\",\"data\":[{\"src\":\""+path+"\"}]}";
			pw.write(json.toString());
			fos.flush();
			fos.close();
			is.close();
		}
		return "none";
	}
}
